<template>
  <div class="login_container">
    <div class="cover"></div>
    <div class="star-container" ref="starContainer"></div>
    <div class="login_box">
      <!--头像区域-->
      <div class="avatar_box">
        <img src="@/assets/logo.jpg" alt="" />
      </div>
      <!-- 表单提交区域-->
      <el-form :rules="loginFormRules" ref="loginFormRef" label-width="0px" class="login_form" :model="loginForm">
        <!-- 用户名 -->
        <el-form-item prop="username">
          <el-input
            v-model="loginForm.username"
            class="w-50 m-2"
            placeholder="username"
      >
      <template #prepend><el-icon><User /></el-icon></template>
    </el-input>
        </el-form-item>
        <!-- 密码-->
        <el-form-item prop="password">
          <el-input
            v-model="loginForm.password"
            class="w-50 m-2"
            type="password"
            placeholder="password"
            pefix-icon="Search"
      >
      <template #prepend>
        <el-icon><Lock /></el-icon>
      </template>
    </el-input>
        </el-form-item>
      </el-form>
      <!--  按钮区-->
      <div class="btns">
        <el-button type="primary" @click="login" :loading="loginLoading">登录</el-button>
        <el-button type="info" @click="resetLoginForm">重置</el-button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
// 流星类
 class Star {
    public container;
    constructor(containerName:string) {
      this.container = document.querySelector(containerName)
      setInterval(() => {
        var newStar = document.createElement("div")
        newStar.className = "star"
        newStar.style.top = this.randomDistance(500, -100) + 'px'
        newStar.style.left = this.randomDistance(1800, 300) + 'px'
        this.container!.appendChild(newStar)
        if (this.container!.children.length > 5) {
            this.container!.removeChild(this.container!.children[0])
        }
    },3000)
    }
    // 流星可以飞的距离
    randomDistance(min:number,max:number) {
      var distance = Math.floor(Math.random() * (max - min + 1) + min)
      return distance
    }
 }


  import {IhttpReturn, loginType} from '../until/interface'
  import {ref,reactive, onMounted} from 'vue'
  import type {FormRules} from 'element-plus'
  import { Search } from '@element-plus/icons-vue'
  import { getCurrentInstance } from 'vue'
  import { userStore } from '../store/user'
  import router from '../router'

  let store = userStore()
  let {proxy} = getCurrentInstance()
  let loginFormRef = ref() // 登录表单的引用
  let loginLoading = ref<boolean>(false) // 登录的状态
  // 用户的登录参数
  let loginForm = reactive<loginType>({
    username: "mega",
    password: "mega1407"
  }) 
  onMounted(() => {
    // 制作流星
    new Star(".star-container")
  })
      // 用户登录
  const login = ():void =>  {
    loginFormRef.value.validate(async (item:any) => {
       if (!item) return proxy.$message({showClose: true,message: "前按照规则进行填写",type: "warning"})
       let {data:res}: {data:IhttpReturn} = await proxy.$outsideHttp.post("/user/login",loginForm)
       if (res.code !== 200)  return proxy.$message({showClose: true,message: res.msg,type: "warning"})
       proxy.$message({showClose: true,message: res.msg,type: "success"})
       store.initUser(res.data)
       router.push("/home")
       // 修改数据库用户的登录状态
       await proxy.$outsideHttp.put("/user/updateLoginStatus",{status: 1,token: res.data.token})

    })
  }

  // 重置登录
  const resetLoginForm = ():void => {
    // 重置表单里面的信息
     loginFormRef.value.resetFields()
  }
  // 验证密码
  const validatePass = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('密码不能为空'))
  } else if (!(/^[a-zA-Z0-9]{6,12}$/.test(value))) {
    callback(new Error("密码为6-12位，有数字和字母组成"))
  } else {
    callback()
  }
}
const validateUser = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('用户名不能为空'))
  } else if (!(/^[a-zA-Z0-9_-]{4,16}$/.test(value))) {
    callback(new Error("4到16位（字母，数字，下划线，减号"))
  } else {
    callback()
  }
}
  let loginFormRules = reactive<FormRules<typeof loginForm>>({
    username: [{ validator: validateUser, trigger: 'blur' }],
    password: [{ validator: validatePass, trigger: 'blur' }],
  })
</script>

<style lang="less" scoped>
.login_container {
  height: 100%;
  background: url("../assets/bg1.jpg") no-repeat center;
  .cover {
    background: #d8d8d8;
    opacity: .1;
    position: absolute;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
  }
}
.login_box {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 20%;
  height: 30%;
  background-color: #fff;
  border-radius: 3px;
  .avatar_box {
    position: absolute;
    left: 50%;
    transform: translate(-50%, -50%);
    padding: 10px;
    width: 140px;
    height: 140px;
    border: 1px solid #eee;
    border-radius: 50%;
    box-shadow: 0 0 10px #ddd;
    background-color: #fff;
    img {
      width: 100%;
      height: 100%;
      border-radius: 50%;
      background-color: #eeeeee;
    }
  }
  .login_form {
    box-sizing: border-box;
    position: absolute;
    height: 60%;
    bottom: 0px;
    width: 100%;
    padding: 0 20px;
  }
  .btns {
      display: flex;
      justify-content: flex-end;
      position: absolute;
      width: 100%;
      bottom: 20px;
      right: 15px;
  }
}

</style>